<?php

namespace app\lnk\controller\api;

use app\lnk\model\CircleModel;
use app\lnk\model\CommentModel;
use app\lnk\model\DynamicModel;
use app\lnk\model\IntegralModel;
use app\lnk\model\UserFollowModel;
use app\lnk\model\DynamicImgModel;
use app\lnk\model\DynamicVideoModel;
use app\lnk\model\UserLikeDynamicModel;
use app\lnk\model\CircleFansModel;
use app\lnk\model\MessageModel;
use app\lnk\model\UserModel;
use app\lnk\service\DynamicService;
use lite\service\ConfigService;
use lite\lib\help;
use think\facade\Db;
use think\Request;

use app\appcenter\lib\AppIHookService;

class Dynamic
{
    public function get_dynamic_info(Request $request)
    {
        $id = $request->get('id');
        $data = DynamicModel::where('id', $id)
            ->field(DynamicService::dynamic_find())
            ->find();
        $data->imgs = DynamicImgModel::where('dynamic_id', $id)
            ->order('weigh', 'asc')
            ->field('url,wide,high')
            ->select();
        $data->video = DynamicVideoModel::where('dynamic_id', $id)
            ->field('url,img,wide,high')
            ->find();

        return success('成功', $data);
    }

    public function recommend_dynamic(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type', 1);
        $city = $request->get('city');
        $order = 'weigh';
        $condition[] = ['status', '=', 1];
        $condition[] = ['show', '=', 1];
        if ($city && $type == 2) $condition[] = ['content|circle_name|province|city|district|adds', 'like', '%' . $city . '%'];
        if ($type == 0) {
            $ids = UserFollowModel::where('user_id', $uid)
                ->column('follow_user_id');
            $condition[] = ['user_id', 'in', $ids];
            $order = 'id';
        }
        if ($type == 2) {
            $condition[] = ['mold', 'in', '10'];
        }
        if ($type == 3) {
            $condition[] = ['mold', 'in', '20'];
        }
        if ($type == 4) {
            $condition[] = ['mold', 'in', '30'];
        }

        $model = [
            'where' => $condition,
            'order' => ['top' => 'desc', 'create_time' => 'desc', $order => 'desc', 'view' => 'desc']
        ];

        AppIHookService::Hook_Run('index_list_dynamic',$model,['uid'=>$uid,'request'=>$request]);

        $data = DynamicModel::where($model['where'])
            ->order($model['order'])
            ->field(DynamicService::dynamic_find())
            ->paginate(6)->toArray();
        $data = DynamicService::dynamic_map($data, true, $uid);
        AppIHookService::Hook_Run('index_list_dynamic_out',$data,['uid'=>$uid,'request'=>$request]);
        return success('成功', $data);
    }

    public function del_dynamic(Request $request)
    {
        $id = $request->post('id');
        DynamicModel::where('id', $id)->update(['status' => 2]);

        return error('已为您删除这篇动态', 600801);
    }

    public function dynamic_details(Request $request)
    {
        $uid = $request->uid;
        $id = $request->get('id');
        $data = DynamicModel::where('id', $id)
            ->field(DynamicService::dynamic_find())
            ->find();
        if (!$data) return error('未找到动态或动态异常', 600201);
        if ($data['circle_id'] && $data['circle_name']) {
            $type = CircleModel::where('id', $data['circle_id'])->value('type');
            if ($type == 1) {
                $isExists = CircleFansModel::where('circle_id', $data['circle_id'])->where('user_id', $uid)->count() ? true : false;
                if (!$isExists) return error('私密圈子动态，请加入圈子后查看', 600502, $data['circle_id']);
            }
        }
        DynamicModel::where('id', $id)->update([
            'weigh' => Db::raw('weigh+1'),
            'view' => Db::raw('view+1'),
        ]);
        AppIHookService::Hook_Run('view_dynamic',$data,['uid'=>$uid,'aid'=>$id,'request'=>$request]);
        $data['user'] = UserModel::where('id', $data['user_id'])
            ->field('name,avatar,career')
            ->find();
        if ($data['type'] == 1) {
            $data['img'] = DynamicImgModel::where('dynamic_id', $data['id'])
                ->order('weigh', 'asc')
                ->field('url,wide,high')
                ->select();
        } else if ($data['type'] == 2) {
            $data['video'] = DynamicVideoModel::where('dynamic_id', $data['id'])
                ->field('url,img,wide,high')
                ->find();
        }
        $data['create_time_text'] = help::time_text($data['create_time']);
        $data['province'] = help::adds_text($data['province']);
        $data['comment_count'] = CommentModel::where('dynamic_id', $data['id'])->count();
        $data['like_count'] = UserLikeDynamicModel::where('dynamic_id', $data['id'])->count();
        $data['is_like'] = UserLikeDynamicModel::where('dynamic_id', $data['id'])
            ->where('user_id', $uid)
            ->where('status', 1)
            ->count() ? true : false;
        $data['fx_title'] = mb_strimwidth($data['content'],0,60,'...','utf-8');
        return success('成功', $data);
    }

    public function like_dynamic(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id');
        $duid = $request->post('duid');
        $is_like = $request->post('is_like');
        $content = $request->post('content');
        $img = $request->post('img');
        if ($is_like) {
            UserLikeDynamicModel::insert([
                'dynamic_id' => $id,
                'user_id' => $uid,
                'status' => 1,
                'create_time' => time()
            ]);
            AppIHookService::Hook_Run('add_dynamic_like',$data,['uid'=>$uid,'aid'=>$id,'request'=>$request]);
            $count = UserLikeDynamicModel::where('dynamic_id', $id)
                ->where('user_id', $uid)
                ->count();
            if ($count > 1 && $duid != $uid) {
                $avatar_url = '/pages/user/details?id=' . $uid;
                $content_url = '/pages/dynamic/details?id=' . $id;
                if (isset($content{40})) {
                    $content = mb_substr($content, 0, 20, "utf-8") . '...';
                }
                (new MessageModel())->send($duid, '动态获赞', $content, $uid, $img, $avatar_url, $content_url, 1);
            }
        } else {
            UserLikeDynamicModel::where('dynamic_id', $id)
                ->where('user_id', $uid)
                ->where('status', 1)
                ->update(['status' => 0]);
            AppIHookService::Hook_Run('cancel_dynamic_like',$data,['uid'=>$uid,'aid'=>$id,'request'=>$request]);
        }
        
        return success('成功', '');
    }

    public function save_dynamic(Request $request)
    {
        $uid = $request->uid;
        $params = $request->post();
        $id = $params['id'];
        $model = ['user_id' => $uid, 'content' => $params['content'], 'circle_id' => $params['circle_id'], 'circle_name' => $params['circle'], 'type' => $params['type']];
        if (!empty($params['adds'])) {
            $model += ['adds' => $params['adds']['name']];
            $model += ['lat' => $params['adds']['latitude']];
            $model += ['lng' => $params['adds']['longitude']];
        }
        $model += ['status' => 0];
        if (!ConfigService::get('lnk', 'lnk_sh_dt', 1)) $model['status'] = 1;
        if ($id) {
            $model += ['update_time' => time()];
            AppIHookService::Hook_Run('edit_dynamic',$model,['uid'=>$uid,'aid'=>$id,'request'=>$request]);
            DynamicModel::where('id', $id)->update($model);
            AppIHookService::Hook_Run('edit_dynamic_out',$model,['uid'=>$uid,'aid'=>$id,'request'=>$request]);
            if ($params['type'] == 1) DynamicImgModel::where('dynamic_id', $id)->delete();
            if ($params['type'] == 2) DynamicVideoModel::where('dynamic_id', $id)->delete();
        } else {
            $model += ['create_time' => time()];
            $ip = $request->ip();
            $model += ['ip' => $ip];
            $res = help::ip($ip);
            if ($res['status'] == 0) {
                if (empty($params['adds'])) {
                    $model += ['lat' => $res['result']['location']['lat']];
                    $model += ['lng' => $res['result']['location']['lng']];
                }
                $model += ['country' => $res['result']['ad_info']['nation']];
                $model += ['province' => $res['result']['ad_info']['province']];
                $model += ['city' => $res['result']['ad_info']['city']];
                $model += ['district' => $res['result']['ad_info']['district']];
            }
            AppIHookService::Hook_Run('add_dynamic',$model,['uid'=>$uid,'request'=>$request]);
            $id = (new DynamicModel)->insertGetId($model);
            AppIHookService::Hook_Run('add_dynamic_out',$model,['uid'=>$uid,'aid'=>$id,'request'=>$request]);

            // 通知圈主
            if ($params['circle_id']) {
                $cinfo = CircleModel::where('id', $params['circle_id'])->field('user_id,avatar')->find();
                if ($cinfo && !empty($cinfo['user_id'])) {
                    $msg = '你的圈子【' . $params['circle'] . '】有一条新的内容待审核，请及时处理。';
                    $img = $cinfo['avatar'];
                    $content_url = '/pages/center/examine?id=' . $params['circle_id'] . '&name=' . $params['circle'];
                    (new MessageModel())->send($cinfo['user_id'], '新内容待审核', $msg, 1, $img, '', $content_url, 0);
                }
            }
        }
        if ($params['type'] == 1 && !empty($params['imgs'])) {
            $img_model = [];
            foreach ($params['imgs'] as $k => $v) {
                $img_model[$k]['url'] = $v['url'];
                $img_model[$k]['wide'] = $v['wide'];
                $img_model[$k]['high'] = $v['high'];
                $img_model[$k]['weigh'] = $k;
                $img_model[$k]['dynamic_id'] = $id;
                $img_model[$k]['user_id'] = $uid;
                $img_model[$k]['status'] = 1;
            }
            DynamicImgModel::insertAll($img_model);
        }
        if ($params['type'] == 2 && !empty($params['video'])) {
            DynamicVideoModel::insert([
                'url' => $params['video']['url'],
                'img' => $params['video']['img'],
                'wide' => $params['video']['wide'],
                'high' => $params['video']['high'],
                'dynamic_id' => $id,
                'user_id' => $uid,
                'update_time' => time()
            ]);
        }

        return success('发布成功 🎉', '');
    }

}
